package com.besttone.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import com.besttone.common.StaticConstantType;
import com.besttone.model.BstReceiveReserve;
import com.jfinal.plugin.activerecord.Page;

public class ReceiveReserve2SolrUtil {

    private static Log _log = LogFactory
	    .getLog(ShortlinkBrowseRecord2SolrUtil.class);
    private static CloudSolrServer cloudSolrServer;

    public static void receiveReserve2Solr() {
	_log.info("启动 receiveReserve solr:" + new Date());
	try {
	    connectCloudSolrServer();
	    addReceiveReserveIndex(cloudSolrServer);
	} catch (Exception e) {
	    _log.error("增量数据入solr异常:" + e);
	}
    }

    /**
     * 获取CloudSolrServer
     * 
     * @param zkHost
     * @return
     */
    private static synchronized CloudSolrServer getCloudSolrServer(
	    final String zkHost) {
	if (cloudSolrServer == null) {
	    try {
		_log.info("创建cloudSolrServer");
		cloudSolrServer = new CloudSolrServer(zkHost);
	    } catch (Exception e) {
		_log.info("cloudSolrServer创建异常:" + e);
	    }
	}
	return cloudSolrServer;
    }

    /**
     * 连接CloudSolrServer
     */
    private static void connectCloudSolrServer() {
	CloudSolrServer cloudSolrServer = getCloudSolrServer(PropertieUtils
		.getProperty("zkHost"));
	_log.info("The Cloud SolrServer Instance has benn created!");
	cloudSolrServer.setDefaultCollection(PropertieUtils
		.getProperty("zqReserveCollection"));
	cloudSolrServer.setZkClientTimeout(Integer.valueOf(PropertieUtils
		.getProperty("zkClientTimeout")));
	cloudSolrServer.setZkConnectTimeout(Integer.valueOf(PropertieUtils
		.getProperty("zkConnectTimeout")));
	cloudSolrServer.connect();
	_log.info("The cloud Server has been connected !!!!");
    }

    /**
     * 添加索引
     * 
     * @param solrServer
     */
    private static void addReceiveReserveIndex(SolrServer solrServer) {
	int page = 1;
	while (true) {
	    Page<BstReceiveReserve> reserveList = BstReceiveReserve.dao
		    .getNotSyncData(page);
	    if (reserveList == null || reserveList.getList().size() == 0)
		break;
	    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
	    if (reserveList.getList().size() > 0) {
		for (BstReceiveReserve detail : reserveList.getList()) {
		    try {
			SolrInputDocument doc1 = new SolrInputDocument();
			doc1.addField("cust_name", detail.getStr("cust_name"));// 唯一ID
			doc1.addField("cust_sex", detail.getStr("cust_sex"));// sex
			doc1.addField("cust_phone", detail.getStr("cust_phone"));// phone
			doc1.addField("reserve_code",
				detail.getStr("reserve_code"));// 优惠券号
			doc1.addField("create_time",
				detail.getTimestamp("create_time").toString());// createtime
			_log.info("doc的field:" + doc1);
			docs.add(doc1);
			detail.set("is_sync", StaticConstantType.IS_SYNC)
				.update();
		    } catch (Exception e) {
			_log.info("创建索引异常：" + e);
		    }
		}
		try {
		    solrServer.add(docs);
		    solrServer.commit();
		} catch (SolrServerException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} catch (Exception e) {
		    _log.error("提交索引异常:" + e);
		}
	    }
	    page++;
	}
    }

    /**
     * 查询索引
     * 
     * @param querySql
     * @param currentPage
     * @param perPageSize
     * @param isReturnDetail
     * @return
     */
    public static SolrDocumentList search(String querySql, Integer currentPage,
	    Integer perPageSize) {
	SolrQuery query = new SolrQuery();
	query.setQuery(querySql);
	query.setStart((currentPage - 1) * perPageSize);
	query.setRows(perPageSize);
	query.setFields("cust_name,cust_sex,cust_phone,reserve_code,create_time");// 查询字段
	query.setSort("create_time", ORDER.desc);
	try {
	    connectCloudSolrServer();
	    QueryResponse response = cloudSolrServer.query(query);
	    SolrDocumentList docs = response.getResults();
	    _log.info("文档个数：" + docs.getNumFound());
	    _log.info("查询时间：" + response.getQTime());
	    return docs;
	} catch (SolrServerException e) {
	    _log.info("SolrServer异常：" + e);
	} catch (Exception e) {
	    _log.info("Solr查询异常：" + e);
	}
	// cloudSolrServer.shutdown();
	return null;
    }

}
